package com.fengzuxiao.weatherdemo.city_manager;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.fengzuxiao.weatherdemo.R;
import com.fengzuxiao.weatherdemo.bean.WeatherBean;
import com.fengzuxiao.weatherdemo.db.DatabaseBean;
import com.google.gson.Gson;

import java.util.List;

public class CityMangerAdapter extends BaseAdapter {
    Context context;
    List<DatabaseBean>mDatabase;

    public CityMangerAdapter(Context context, List<DatabaseBean> mDatabase) {
        this.context = context;
        this.mDatabase = mDatabase;
    }

    @Override
    public int getCount() {
        return mDatabase.size();
    }

    @Override
    public Object getItem(int position) {
        return mDatabase.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.item_city_manger,null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        DatabaseBean bean = mDatabase.get(position);
        holder.cityTv.setText(bean.getCity());
        WeatherBean weatherBean = new Gson().fromJson(bean.getContent(), WeatherBean.class);
        //获取今日天气情况
        WeatherBean.ResultsBean.WeatherDataBean dataBean = weatherBean.getResults().get(0).getWeather_data().get(0);
        holder.conTv.setText("天气："+dataBean.getWeather());
        String[] split = dataBean.getDate().split("：");
        String todayTemp = split[1].replace(")", "");
        holder.tempTv.setText(todayTemp);
        holder.windTv.setText(dataBean.getWind());
        holder.tempRangeTv.setText(dataBean.getTemperature());
        return convertView;
    }

    class ViewHolder{
        TextView cityTv,conTv,tempTv,windTv,tempRangeTv;
        public ViewHolder(View itemView){
            cityTv = itemView.findViewById(R.id.item_tv_city);
            conTv = itemView.findViewById(R.id.item_tv_condition);
            tempTv = itemView.findViewById(R.id.item_tv_temp);
            tempRangeTv = itemView.findViewById(R.id.item_tv_tempRange);
            windTv = itemView.findViewById(R.id.item_tv_wind);
        }
    }
}
